import time


class TimeElapsed:
    def __init__(self, name):
        self.name = name
        self.data = []  # 存储每次操作的耗时（微秒）

    def start(self):
        self.start_time = time.perf_counter()  # 开始计时，使用perf_counter获取更高精度的时间

    def end(self):
        elapsed_seconds = time.perf_counter() - self.start_time  # 结束计时，计算耗时（秒）
        elapsed_microseconds = elapsed_seconds * 1e6  # 转换为微秒
        self.data.append(elapsed_microseconds)  # 存储耗时

    def avg(self):
        if self.data:
            average_microseconds = sum(self.data) / len(self.data)  # 平均耗时（微秒）
            return average_microseconds, len(self.data)
        else:
            return 0, 0

    def show(self):
        avg_time, count = self.avg()
        avg_time = avg_time / 1000
        print(f"{self.name} 运行了{count}次，平均耗时约为{avg_time:.2f}ms")


allTimer = {}
def getTimer(name):
    if name not in allTimer:
        allTimer[name] = TimeElapsed(name)
    return allTimer[name]

# # 示例使用
# if __name__ == "__main__":
#     timer = TimeElapsed("示例函数")
#     for _ in range(5):
#         timer.start()
#         # 这里放置您想要计时的代码块
#         time.sleep(0.001)  # 示例代码，模拟耗时操作
#         timer.end()
#     timer.show()
